import axios from 'axios'
import router from '@/router'
import { Message, Loading, Notification } from 'element-ui'

let loading

const http = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

function startLoading () {
  loading = Loading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
function endLoading () {
  loading.close()
}

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  let url = config.url.substr(0, 11)
  if (url === '/tqw/client') {
    if (localStorage.getItem('token') != null) {
      config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token') // 请求头带上token
    }
    return config
  }
  startLoading()
  if (localStorage.getItem('token') != null) {
    config.headers['Authorization'] = 'Bearer '+localStorage.getItem('token') // 请求头带上token
  }
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  endLoading()
  if (response.headers.token) {
    localStorage.setItem("token", response.headers.token)
    location.reload()
  }
  if (response.data.code === 401) {
    debugger
    Notification.error({ title: '错误', message: '登录已失效请重新登录', duration: 2500 })
    localStorage.removeItem('token')
    router.push('/index')
  }
  return response
}, error => {
  return Promise.reject(error)
})
export default http
